package com.lh1010.s2.controller;

import com.lh1010.s2.pojo.Article;
import com.lh1010.s2.pojo.Result;
import com.lh1010.s2.pojo.User;
import com.lh1010.s2.service.ArticleService;
import com.lh1010.s2.service.UserService;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class HomeController {

    // 输出index
    @RequestMapping("/index")
    public String index1(HttpServletRequest request) {
        System.out.println("index");
        return "this is index";
    }

    // 传输参数1
    @RequestMapping("/testParam")
    public String testParam(HttpServletRequest request) {
        String name = request.getParameter("name");
        String age_str = request.getParameter("age");

        int age = Integer.parseInt(age_str);

        System.out.println(name + "：" + age);
        return "testParam ok";
    }

    // 传输参数2
    @RequestMapping("/testParam2")
    public String testParam2(String name, Integer age) {
        System.out.println(name + "：" + age);
        return "testParam2 ok";
    }

    // 使用Result输出
    @RequestMapping("/testParam3")
    public Result testParam3(String name, Integer age) {
        System.out.println(name + "：" + age);
        //return Result.success(code: 1, message: "success", data: 'testParam3 ok');
        return Result.success("testParam3 ok");
    }

    // 返回用户列表
    // Controller -> UserService -> UserServiceImpl -> UserDao -> UserDaoImpl -> UserMapper
    @Autowired // 运行时，IOC容器会提供该类型的bean对象，并赋值给该变量
    private UserService userService; // 可放在上方
    @RequestMapping("/getUsers")
    public Result getUsers() {
        // 调用service获取数据
        List<User> userList = userService.listUser();

        // 响应数据
        return Result.success(userList);
    }

    // 查询一篇文章
    // Controller -> ArticleService -> ArticleServiceImpl -> ArticleMapper
    @Autowired
    private ArticleService articleService;
    @RequestMapping("/getArticle")
    public Article getArticle(Integer id) {
        return articleService.getArticle(id);
    }
}
